import { defineConfig ,loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import autoprefixer from 'autoprefixer';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { createHtmlPlugin } from 'vite-plugin-html';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig(({ command, mode }) => {
  const root = process.cwd()
  const env = loadEnv(mode, root, ['VUE_APP_', 'VITE_'])
  const { VITE_PORT } = env;

  const myDefine: Record<string, string> = {}
  Object.keys({ ...env }).map((key) => {
    const value = env[key]
    myDefine[`process.env.${key}`] = JSON.stringify(value)
  })

  const isProd = mode === 'production';
  return {
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      createHtmlPlugin({
        inject: {
          data: {
            //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
            title: env.VITE_APP_TITLE,
            injectScript: Number(env.VITE_CONSOLE_DEBUGGER)? '<script src="https://cdn.133.cn/ticket/h5/lib/eruda-2.4.1.js"></script><script>window.eruda.init()</script>': '',
          },
        },
      }),
    ],
    resolve: {
      alias: {
        '@': '/src',
      }
    },
    envPrefix: ['VUE_APP_', 'VITE_'],
    server: {
      // Listening on all local IPs
      host: true,
      port: Number(VITE_PORT),
      strictPort: true,
    },
    define: {
      // 注入环境变量，兼容原vue-cli配置，后面可以考虑删除
      ...myDefine,
    },
    manifest: true,
    assetsDir: 'static/img',
    minify: 'terser',
    build: {
      manifest: true,
      assetsDir: 'static/img',
      minify: 'terser',
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
        },
      },
      terserOptions: {
        compress: {
          drop_console: isProd, // 关闭 console.log
          drop_debugger: isProd // 关闭 debugger
        }
      }
    },
    css: {
      preprocessorOptions: { css: { charset: false }, scss: { charset: false } },
      postcss: {
        plugins: [autoprefixer({
          overrideBrowserslist: [
            "Android 4.1",
            "iOS 7.1",
            "Chrome > 31",
            "ff > 31",
            "ie >= 8"
          ],
          grid: true
        })],
      },
    },
  }
})

